<!--用户登录注册-->
<template>
  <div id="register">
    <div class="register-box">
      <!-- tab切换 -->
      <div class="typeChange">
        <div class="typeTab" :class="typeTabIndex == 1 ? 'active' : ''" @click="clicktypeTab(1)">登录</div>
        <div class="typeTab" :class="typeTabIndex == 2 ? 'active' : ''" @click="clicktypeTab(2)">注册</div>
      </div>
      <!-- 普通用户登录 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model.number="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="name2" v-if="typeTabIndex == 2">
          <el-input v-model="ruleForm.name2" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age" v-if="typeTabIndex == 2">
          <el-input v-model="ruleForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" v-if="typeTabIndex == 2">
          <el-input v-model="ruleForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex " v-if="typeTabIndex == 2">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input class="code-input" type="password" v-model="ruleForm.code" autocomplete="off"></el-input>
          <div
            class="codeImg"
            @click="getcode()"
            style="width:100px;height:50px;background:white;float:right"
          >
            <img class="autoCode" :src="codeImg" alt="验证码" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :plain="true"
            @click="LoginForm('ruleForm')"
            v-if="typeTabIndex == 1"
          >登录</el-button>
          <el-button
            type="primary"
            :plain="true"
            @click="RegisterForm('ruleForm')"
            v-if="typeTabIndex == 2"
          >注册</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import userModel from "../request/index";
import axios from "../request/axios";
import cookie from "js-cookie";
export default {
  data() {
    //验证规则
    var name = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else {
        if (/[\w\u4e00-\u9fa5]{2,6}/.test(value)) {
          return callback();
        } else {
          return callback(new Error("用户名必须为6-12位字母/数字/中文"));
        }
      }
    };
    var name2 = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("昵称不能为空"));
      } else {
        if (/[\w\u4e00-\u9fa5]{2,6}/.test(value)) {
          return callback();
        } else {
          return callback(new Error("昵称必须为6-12位字母/数字/中文"));
        }
      }
    };
    var age = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("年龄不能为空"));
      } else {
        if (/^(([0-9]|[1-9][1-9]|1[0-7][0-9])(\\.[0-9]+)?|180)$/.test(value)) {
          return callback();
        } else {
          return callback(new Error("请输入合法年龄"));
        }
      }
    };
    var email = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      } else {
        if (/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
          return callback();
        } else {
          return callback(new Error("请输入正确的邮箱格式"));
        }
      }
    };
    var pass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (/^[a-z0-9]{5,12}$/.test(value)) {
          callback();
        } else {
          callback(new Error("密码必须为字母开头6-12位数字字母组成"));
        }
      }
    };
    var sex = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请勾选性别"));
      }
    };
    var code = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else {
        if (/^[a-z0-9]{5,12}$/.test(value)) {
          callback();
        } else {
          callback(new Error("验证码有误"));
        }
      }
    };
    return {
      // 验证码图片
      codeImg: "",
      // 普通用户字段名
      ruleForm: {
        name: "",
        name2: "",
        age: "",
        email: "",
        pass: "",
        sex: "",
        code: ""
      },
      rules: {
        name: [{ validator: name, trigger: "blur" }],
        name2: [{ validator: name2, trigger: "blur" }],
        age: [{ validator: age, trigger: "blur" }],
        email: [{ validator: email, trigger: "blur" }],
        pass: [{ validator: pass, trigger: "blur" }],
        sex: [{ validator: sex, trigger: "blur" }],
        code: [{ validator: code, trigger: "blur" }]
      },
      //tab切换下标
      typeTabIndex: 1
    };
  },

  //页面的事件和方法
  methods: {
    // 登录验证
    LoginForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          userModel
            .Userquery({
              userName: this.ruleForm.name,
              password: this.ruleForm.pass,
              txt: this.ruleForm.code
            })
            .then(res => {
              console.log("asdasd"+new XMLHttpRequest().getAllResponseHeaders('Set-Cookie'))
            
              if (res !=null && res.data.success == true) {
                this.$message.success("登录成功!");
                //注册成功跳转首页
                this.$router.push({ path: "/" });
                // 将用户信息存到本地
                let userinfo = res.data.result;
                cookie.set("satoken",userinfo.token)
                userinfo = JSON.stringify(userinfo);
                window.localStorage.setItem("userinfo", userinfo);
              } else {
                if(res!=null)
                this.$message.error(res.data.message);
              }
            });
        } else {
          this.$message.error("请检查您的用户信息是否完整或正确!");
          return false;
        }
      });
    },

    //注册验证
    RegisterForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          userModel
            .Useradd({
              userName: this.ruleForm.name,
              nikName: this.ruleForm.name2,
              age: this.ruleForm.age,
              email: this.ruleForm.email,
              passWord: this.ruleForm.pass,
              sex: this.ruleForm.sex,
              txt: this.ruleForm.code
            })
            .then(res => {
             
              if (res.data.success == true) {
                this.$message.success("注册成功!");
                // 注册成功跳到登录
                this.typeTabIndex = 1;
              } else {
                this.$message.error(res.data.message);
              }
            });
        } else {
          this.$message.error("网络错误！");
          return false;
        }
      });
    },

    //点击获取验证码
    getcode() {
        this.codeImg = axios.defaults.baseURL+"file/getImg" + "?data = " + new Date().getTime();
    },

    //重置信息
    resetForm(ruleForm) {
      this.$refs[ruleForm].resetFields();
    },

    //tab切换
    clicktypeTab(i) {
      this.typeTabIndex = i;
    }
  },

  //生命周期（页面加载时执行）
  created() {
    // 页面加载时生成验证码
     this.codeImg = axios.defaults.baseURL+"file/getImg" + "?data = " + new Date().getTime();
  }
};
</script>

<style lang="scss" scoped>
@import "../css/RegisterAndLogin.scss";
.autoCode {
  width: 100%;
  height: 100%;
}
</style>
